import { Directive, ElementRef, HostListener, Input } from '@angular/core';
import { NgControl, NgModel } from '@angular/forms';

@Directive({
  selector: 'input[LengthLimit]',
  inputs: ['LengthLimit']
})
export class LengthLimitDirective {
  LengthLimit:number;
  constructor(
    private el: ElementRef, 
    public ngControl: NgControl,
    public ngModel: NgModel
  ) {
    
   }
   @HostListener('input',['$event']) onInput(event) {
    let input = event.target;
    if ((input.value.length) >= this.LengthLimit || 100) {
      const cutValue = input.value.substr(0,this.LengthLimit || 100);
      this.ngControl.control.patchValue(cutValue); // 如果用表单， 需要patchValue更新表单的值
      this.ngModel.viewToModelUpdate(cutValue); // 如果用ngModel，可以直接用viewToModelUpdate
    }
  }
}
